package com.winchain.chainbill.bill.biz.transfer.cmd;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.framework.command.CallbackContext;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICallback;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.bill.base.po.CbRcv;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.po.CbXfe;
import com.winchain.chainbill.bill.base.service.CbRcvService;
import com.winchain.chainbill.bill.biz.Bill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillRcv4XfeCmd implements ICommand<Bill<CbXfe>>, ICallback<Bill<CbXfe>, AcctTxRec> {
	@Autowired
	private CbRcvService cbRcvService;

	public boolean callback(CallbackContext<Bill<CbXfe>, AcctTxRec> context) throws Exception {
		execute(context);
		return false;
	}

	private CbRcv getRcv(CbRec record, CbXfe xfe) {
		String RcvState = "1";
		if (xfe.getSellerId().equals(xfe.getBuyerId())) {
			RcvState = "2";
		}
		CbRcv rcv = new CbRcv();
		rcv.setRcvId(SystemUtil.getUUID());
		rcv.setBillId(record.getBillId());
		rcv.setCreateTime(DateUtil.getSystemDateTime());
		rcv.setSellerId(xfe.getSellerId());
		rcv.setSellerNm(xfe.getSellerNm());

		rcv.setTxDate(xfe.getXfeDate());
		rcv.setBuyerId(xfe.getBuyerId());
		rcv.setBuyerNm(xfe.getBuyerNm());
		rcv.setRcvState(RcvState);
		rcv.setOptSeq(record.getOptSeq());
		rcv.setRemark(xfe.getRemark());
		rcv.setTxType("1");
		rcv.setTxId(xfe.getXfeId());
		rcv.setRcvLvl(xfe.getHldrLvl());
		return rcv;
	}

	public boolean execute(CommandContext<Bill<CbXfe>> context) throws Exception {
		CbRec record = ((Bill) context.getSource()).getRec();
		CbXfe xfe = (CbXfe) ((Bill) context.getSource()).getSource();
		if (xfe.getXfeId() == null) {
			String ownerId = (String) context.getValue("OwnerId");
			String ownerName = (String) context.getValue("OwnerName");

			xfe = new CbXfe();
			xfe.setSellerId(ownerId);
			xfe.setSellerNm(ownerName);

			xfe.setBuyerId(ownerId);
			xfe.setBuyerNm(ownerName);
		}
		CbRcv intput = getRcv(record, xfe);

		this.cbRcvService.save(intput);
		return false;
	}
}
